/*
 * 创建组件的整体的导出文件
 * */
import { resolve } from "path";
import { FsFile } from "./utils/FsFile.js";
import { log } from "./utils/utils.js";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = resolve(dirname(__filename), "../packages");

// 文件根目录
const FILE_ROOT_PATH = __dirname;

// 创建文件对象
const fsFile = new FsFile(FILE_ROOT_PATH);

export async function createIndexTs() {
  const filePath = resolve(FILE_ROOT_PATH, "index.ts");
  const fileContent = fsFile.getFileContent(filePath);
  const endSymbol = `export default ThDesign;\r\n`;
  if (!fileContent.includes(endSymbol)) {
    log.error("错误：index.ts文件格式不正确");
    return false;
  }
  const fileArr = fileContent.split(endSymbol); // 根据结束符分割文件内容
  const exportAll = fileArr[0];
  let exportComponents = fileArr[1].split("\r\n").filter(item => item !== ""); // 单独导出的组件列表
  const componentPath = resolve(__dirname, "components"); // 组件文件夹
  const componentList = await fsFile.getFolderNames(componentPath); // 获取文件夹列表,组件列表
  // 生成导出组件的代码
  const componentLine = componentList.map(item => {
    return `export * from "./components/${item}/${item}";`;
  });
  // 排除现在已经被删除的组件
  const afterDeleteComponents = exportComponents.filter(item => componentLine.includes(item));
  // 找出现有的导出不存在的组件
  const notExportComponents = componentLine.filter(item => !exportComponents.includes(item));
  if (notExportComponents.length === 0 && afterDeleteComponents.length === exportComponents.length) return log.info("导出组件相同无需修改");
  exportComponents = afterDeleteComponents;
  // 插入到导出组件列表的倒数第二项
  exportComponents.push(...notExportComponents);
  const newExportLines = exportComponents.join("\r\n");
  const newFileContent = exportAll + endSymbol + newExportLines;
  await fsFile.createFile(filePath, newFileContent);
}

await createIndexTs();
